//
// Created by Administrator on 2018/11/1.
//

#ifndef VIDEODEMO_MEDIAPLAY_H
#define VIDEODEMO_MEDIAPLAY_H
#include <iostream>
#include <queue>
#include <thread>
#include <Log.h>

using namespace std;


#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"nativeLog",FORMAT,##__VA_ARGS__);

class VideoDecoder{
private:
    AVCodecContext *pAVCodecCtx;
    AVFrame * pAVFrame=av_frame_alloc();
    AVFrame * rgbFrame=av_frame_alloc();
    SwsContext * pSwsCtx;
    ANativeWindow * aNativeWindow;
    ANativeWindow_Buffer windowBuffer;
    uint8_t * preFramePts;

public:
    void init(AVCodecContext *pAVCodecCtx,ANativeWindow * aNativeWindow);
    void decoder(AVPacket *pAVPacket);

};

class AudioDecoder{
private:
    JNIEnv *env;
    jobject instance;
    jmethodID playTrackId;
    int64_t  preFramePts=0;

    AVCodecContext *pAVCodecCtx;
    SwrContext *pSwrCtx = swr_alloc();
    uint8_t *outBuffer=(uint8_t *) av_malloc(44100 * 2);
    int outChLayoutNb;
    AVSampleFormat  outSampleFmt;
    AVFrame * avFrame = av_frame_alloc();
public:
    void init(JavaVM * javaVM,jobject instance,AVCodecContext *pAVCodecCtx);

    void decoder(AVPacket *pAVPacket);
};

class MediaPlay{
private:
    int videoStream=-1;
    int audioStream=-1;
    AVCodecContext * pAVCodecAudioCtx=NULL;
    AVCodecContext * pAVCodecVideoCtx=NULL;
    queue<AVPacket> audioPacketQueue;
    queue<AVPacket> videoPacketQueue;
    VideoDecoder videoDecoder;
    AudioDecoder audioDecoder;
    ANativeWindow * pANativeWindow;
    AVFormatContext *pAVFormatCtx = avformat_alloc_context();
    JavaVM * javaVM;
    jobject instance;
public:

    void setDataSource(JavaVM *javaVM, jobject instance, const char * filePath,ANativeWindow * pANativeWindow);

    void read();

    void videoDecoderFunc();

    void audioDecoderFunc();


};


#endif //VIDEODEMO_MEDIAPLAY_H
